import PageableCollection from 'backbone.paginator';

import BaseProductModel from './BaseProductModel.js';
import ProductWorkModel from './ProductWorkModel.js';
import TrainingModel from './TrainingModel.js';
import VAEModel from './VAEModel.js'

const ProductCollection = PageableCollection.extend({
    model(modeldict, options) {
        if (modeldict.type_ === 'sale_product_work') {
            return new ProductWorkModel(modeldict, options);
        } else if (modeldict.type_ === 'sale_product_training') {
            return new TrainingModel(modeldict, options);
        } else if (modeldict.type_ === 'sale_product_vae') {
            return new VAEModel(modeldict, options);
        } else {
            return new BaseProductModel(modeldict, options);
        }
    },
    state: {
        firstPage: 0,
        pageSize: 10
    },
    queryParams: {
        currentPage: "page",
        pageSize: "items_per_page"
    },
    updatePageSize(items_per_page) {
        this.setPageSize(items_per_page);
    },
    updateParams(query_params) {
        _.extend(this.queryParams, query_params);
    },
    buildModel(modelDict, response) {
        this.add([modelDict]);
        return this.get(modelDict['id']);
    },
    fetchSingle(modelId) {
        /*
        Fetch a single model and returns a promise resolving the model

        collection.fetchSingle(id).then(
            function(model){console.log(model.get('name'))}
        );
        */
        let result
        let model = this.get(modelId);
        if (_.isUndefined(model)) {
            // On fetche le modèle en utilisant un BaseProductModel et on recrée 
            // un modèle en utilisant la collection qui va créer le bon type de produit
            model = new BaseProductModel({
                id: modelId
            }, {
                collection: this
            });
            model.url = this.url + '/' + modelId;
            result = model.fetch();
            result = result.then(this.buildModel.bind(this));
        } else {
            result = $.Deferred();
            result.resolve(model, null, null);
        }
        return result;
    }
});
export default ProductCollection;
